package com.example.myapplication3.image;


import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.example.myapplication3.image.bean.ImageItem;
import com.example.myapplication3.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 图像资源查询业务类
 *
 * @author yuanc
 * @Description: (用一句话描述)
 * @date 2025/8/9 19:32
 */
public class ImageQueryHelper {
    private static final String TAG = "ImageQueryHelper";
    private static final ExecutorService executor = Executors.newFixedThreadPool(2);

    /**
     * 获取所有图片信息（兼容所有Android版本）
     */
    public static void asynLoadAllImages(Context context, int pageIndex, int itemCount) {
        executor.execute(() -> {
            List<ImageItem> images = new ArrayList<>();

            // 定义要查询的列
            String[] projection = {
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.SIZE,
                    MediaStore.Images.Media.DATE_ADDED,
                    MediaStore.Images.Media.DATE_MODIFIED,
                    MediaStore.Images.Media.MIME_TYPE,
                    MediaStore.Images.Media.WIDTH,
                    MediaStore.Images.Media.HEIGHT
            };

            // 只查询相机拍摄的照片
            String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " = 'Camera'";

            // 按日期降序排序
            String sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC";

            // 媒体文件图像的URI
            Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(
                    mediaUri,
                    projection,
                    null,
                    null,
                    sortOrder
            );
            if (cursor != null) {
                try {
                    // TODO: 定位
                    cursor.moveToPosition(pageIndex * itemCount);
                    while (cursor.moveToNext()) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
                        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                        long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE));
                        long dateAdded = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED));
                        long dateModified = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED));
                        String mime = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE));
                        int width = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH));
                        int height = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT));
                        Uri uri = ContentUris.withAppendedId(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                id
                        );
                        // 构造图像
                        ImageItem item = new ImageItem(
                                id,
                                name,
                                path,
                                uri,
                                size,
                                dateAdded,
                                dateModified,
                                mime,
                                width,
                                height
                        );
                        images.add(item);
                        // TODO: 定量
                        if (images.size() >= itemCount) {
                            break;
                        }
                    }

                } catch (Exception e) {
                    LogUtils.e(TAG, "获取图片失败", e);
                    loadCallback.onImagesLoaded(null);
                } finally {
                    cursor.close();
                }
            }
            // 结果返回
            if (loadCallback != null)
                loadCallback.onImagesLoaded(images);
        });
    }

    /**
     * 使用系统应用打开图像
     */

    private static ImageLoadCallback loadCallback;

    public static void setImageLoadCallback(ImageLoadCallback loadCallback) {
        ImageQueryHelper.loadCallback = loadCallback;
    }

    public interface ImageLoadCallback {
        void onImagesLoaded(List<ImageItem> images);
    }
}